package com.sky.mybatis.generator.types;

import com.sky.mybatis.generator.column.EncryptAbleIntrospectedColumn;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl;

import java.util.Objects;

/**
 * 修改生成的代码中需要加解密字段的类型
 */
public class EncryptAbleJavaTypeResolver extends JavaTypeResolverDefaultImpl {

    private static final String ENCRYPT_CLAZZ_KEY = "javaEncryptClass";
    @Override
    protected FullyQualifiedJavaType overrideDefaultType(IntrospectedColumn column, FullyQualifiedJavaType defaultType) {
        // 解析是否为加解密类型，加解密类型返回指定的class类型
        FullyQualifiedJavaType decryptAbleType = overrideEncryptAbleType(column, defaultType);
        if (decryptAbleType != null) {
            return decryptAbleType;
        }
        return super.overrideDefaultType(column, defaultType);
    }

    protected FullyQualifiedJavaType overrideEncryptAbleType(IntrospectedColumn column, FullyQualifiedJavaType defaultType) {
        if (!(column instanceof EncryptAbleIntrospectedColumn)){
            return null;
        }
        EncryptAbleIntrospectedColumn encryColumn = (EncryptAbleIntrospectedColumn) column;
        // 填写的加密的字段名称
        String encryptColumAlias = encryColumn.getEncryptColums();
        String encryptColumType = column.getContext().getProperty(ENCRYPT_CLAZZ_KEY);
        if(isEmpty(encryptColumAlias) || isEmpty(encryptColumType)){
            return null;
        }
        String[] encryptColums = encryptColumAlias.split(",");

        boolean isInEncryptColumn = isInEncryptColumn(encryptColums,column.getActualColumnName());
        if(isInEncryptColumn){
            return new FullyQualifiedJavaType(encryptColumType);
        }
        return null;
    }

    private boolean isEmpty(String str){
        return str == null || str.isEmpty();
    }

    /**
     * 判断该字段是否为加解密字段
     * @param encryptColums
     * @param actualColumnName
     * @return
     */
    private boolean isInEncryptColumn(String[] encryptColums, String actualColumnName) {
        for (int i = 0; i < encryptColums.length; i++) {
            String encryptColum = encryptColums[i];
            if(Objects.equals(actualColumnName,encryptColum)){
                return true;
            }
        }
        return false;
    }
}
